package com.kws.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.common.config.constant.MinioCommonBucket;
import com.kws.common.config.util.DateTimeUtil;
import com.kws.common.core.enums.ModelOpType;
import com.kws.common.core.exception.ServiceException;
import com.kws.common.core.sys.Ksys;
import com.kws.common.core.utils.KConstants;
import com.kws.common.core.utils.StringUtils;
import com.kws.common.redis.service.RedisService;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.system.api.enumDo.RedisConstant;
import com.kws.system.config.MinioAPI;
import com.kws.system.domain.SysCompanyMessage;
import com.kws.system.domain.vo.CreateCompanyMessageRq;
import com.kws.system.mapper.SysCompanyMessageMapper;
import com.kws.system.service.SysCompanyMessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDate;

/**
 * <b>SysCompanyMessageServiceImpl</b>
 *
 * @description: SysCompanyMessageServiceImpl <br>
 * @date: 2024/10/25 11:54 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class SysCompanyMessageServiceImpl extends ServiceImpl<SysCompanyMessageMapper, SysCompanyMessage> implements SysCompanyMessageService {
    private static final Logger logger = LoggerFactory.getLogger(SysCompanyMessageServiceImpl.class);

    @Autowired
    private MinioAPI minioAPI;
    @Autowired
    private RedisService redisService;

    private final static String SLASH = "/";

    private final static String FILE_NAME_PREFIX_SEPARATOR = "-";

    @Value("${minio.ENDPOINT}")
    private String minioUrl;

    @Override
    public boolean checkLoginCompany(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",userId);
        SysCompanyMessage sysCompanyMessage = baseMapper.selectOne(queryWrapper);
        if (null != sysCompanyMessage){
            return true;
        }
        return false;
    }

    @Override
    public boolean createCompanyMessage(CreateCompanyMessageRq rq) {
        Long userId = SecurityUtils.getUserId();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",userId);
        SysCompanyMessage sysCompanyMessage1 = baseMapper.selectOne(queryWrapper);
        if (null != sysCompanyMessage1){
            new ServiceException("该用户已申请企业，请勿重新申请！");
        }
        SysCompanyMessage sysCompanyMessage = new SysCompanyMessage();
        sysCompanyMessage.setUserId(SecurityUtils.getUserId());
        sysCompanyMessage.setCommercialType(rq.getCommercialType());
        if (CollectionUtil.isNotEmpty(rq.getUserRoleList()) && rq.getUserRoleList().size() == 1){
            String userRole = rq.getUserRoleList().get(0);
            sysCompanyMessage.setUserRole(userRole);
        }else if (CollectionUtil.isNotEmpty(rq.getUserRoleList())){
            String userRole = rq.getUserRoleList().get(0);
            for (int i = 1; i < rq.getUserRoleList().size(); i++) {
                userRole = userRole +","+rq.getUserRoleList().get(i);
            }
            sysCompanyMessage.setUserRole(userRole);
        }
        sysCompanyMessage.setContactPerson(rq.getContactPerson());
        sysCompanyMessage.setContactInformation(rq.getContactInformation());
        sysCompanyMessage.setCorporateName(rq.getCorporateName());
        sysCompanyMessage.setDocumentType(rq.getDocumentType());
        sysCompanyMessage.setDocumentNumber(rq.getDocumentNumber());
        sysCompanyMessage.setDocumentPicture1Url(rq.getDocumentPicture1Url());
        sysCompanyMessage.setDocumentPicture2Url(rq.getDocumentPicture2Url());
        sysCompanyMessage.setBusinessLicenseUrl(rq.getBusinessLicenseUrl());
        sysCompanyMessage.setMerchantCertificationType(rq.getMerchantCertificationType());
        sysCompanyMessage.setAptitudeCertificate1Url(rq.getAptitudeCertificate1Url());
        sysCompanyMessage.setAptitudeCertificate2Url(rq.getAptitudeCertificate2Url());
        sysCompanyMessage.setAptitudeCertificate3Url(rq.getAptitudeCertificate3Url());
        sysCompanyMessage.setCompanyName(rq.getCompanyName());
        sysCompanyMessage.setCompanyAddress(rq.getCompanyAddress());
        if (CollectionUtil.isNotEmpty(rq.getBusinessScopeList()) && rq.getBusinessScopeList().size() == 1){
            String businessScope = rq.getBusinessScopeList().get(0);
            sysCompanyMessage.setBusinessScope(businessScope);
        }else if (CollectionUtil.isNotEmpty(rq.getBusinessScopeList())){
            String businessScope = rq.getBusinessScopeList().get(0);
            for (int i = 1; i < rq.getBusinessScopeList().size(); i++) {
                businessScope = businessScope +","+rq.getBusinessScopeList().get(i);
            }
            sysCompanyMessage.setBusinessScope(businessScope);
        }
        sysCompanyMessage.setRegistrationCertificateNumber(rq.getRegistrationCertificateNumber());
        sysCompanyMessage.setBankCardType(rq.getBankCardType());
        sysCompanyMessage.setAccountBankName(rq.getAccountBankName());
        sysCompanyMessage.setBankAccountNumber(rq.getBankAccountNumber());
        //提交状态为待审核
        sysCompanyMessage.setStatus(2);
        //账号状态为不可用
        sysCompanyMessage.setEnable("0");
        //创建用户
        sysCompanyMessage.setCreateUser(userId);
        Ksys.setBasicModelData(sysCompanyMessage,SecurityUtils.getStringUserId(), KConstants.DATA_ENABLE, ModelOpType.CREATE);
        int insert = baseMapper.insert(sysCompanyMessage);
        if (insert == 1){
            return true;
        }
        return false;
    }

    @Override
    public String uploadCompanyFile(MultipartFile file) {
        try (InputStream is = file.getInputStream()) {
            String bucketName = MinioCommonBucket.HUATAI_PUB_BUCKET;
            String objectKey = getObjectKey(file.getSize(), file.getOriginalFilename());
            minioAPI.uploadInputStream(bucketName, objectKey, is, file.getContentType());
            logger.info("上传地址为:{}"+objectKey);
            return minioUrl+"/"+MinioCommonBucket.HUATAI_PUB_BUCKET+"/"+objectKey;
        } catch (Exception e) {
            logger.error("上传失败，", e);
            throw new ServiceException("上传失败，请重新上传");
        }
    }

    @Override
    public SysCompanyMessage queryCompanyMessageByUserId(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",userId);
        SysCompanyMessage sysCompanyMessage = baseMapper.selectOne(queryWrapper);
        return sysCompanyMessage;
    }

    /**
     * 审核
     * @param checkVo
     * @return
     */
    /*@Override
    public Object check(CheckVo checkVo) {
        Long id = checkVo.getId();
        Long userId = SecurityUtils.getUserId();
        SysCompanyMessage companyMessage = this.getById(id);
        if (ObjectUtils.isEmpty(companyMessage)){
            throw new RuntimeException("没有查到改商家提交的入驻申请");
        }
        Integer status = checkVo.getStatus();
        String approvalOpinion = checkVo.getApprovalOpinion();
        companyMessage.setStatus(status);
        companyMessage.setApprovalOpinion(approvalOpinion);
        //审核通过，改变账号状态为正常
        if (status==0){
            companyMessage.setEnable("0");
            companyMessage.setUpdateUser(userId);
            //加入缓存
            redisService.setCacheObject(RedisConstant.COMPANY_MESSAGE.getCode()+userId, companyMessage);
        }

        return this.updateById(companyMessage);
    }*/

    /**
     * 商家入驻信息分页
     * @param sysCompanyMessagePo
     * @return
     */
   /* @Override
    public Page<SysCompanyMessage> pageList(SysCompanyMessagePo sysCompanyMessagePo) {
        Page<SysCompanyMessage> page = new Page<>(sysCompanyMessagePo.getPageSize(), sysCompanyMessagePo.getTotalPage());
        LambdaQueryWrapper<SysCompanyMessage> queryWrapper = Wrappers.<SysCompanyMessage>lambdaQuery();
        String name = sysCompanyMessagePo.getName();//名称
        String status = sysCompanyMessagePo.getStatus();//状态
        String role = sysCompanyMessagePo.getName();//入驻角色
        if (StringUtils.isNotEmpty(name)){
            queryWrapper.eq(SysCompanyMessage::getCompanyName,name);
        }
        if (StringUtils.isNotEmpty(status)){
            queryWrapper.eq(SysCompanyMessage::getStatus,status);
        }
        if (StringUtils.isNotEmpty(role)){
            queryWrapper.like(SysCompanyMessage::getUserRole,role);
        }
        return this.page(page, queryWrapper);
    }*/

    /**
     * 商家数据统计-昨日
     * @return
     */
    @Override
    public Object statistics() {
        //todo
        //支付金额
        //访客数
        //浏览量
        //加购人数
        //浏览商品数
        //收藏商品数
        //昨日收藏人数
        //支付买家数
        //订单数
        //昨日总收入
        //昨日总支出
        //昨日在途订单数
        //昨日在途订单金额

        return null;
    }

    private String getObjectKey(Long fileSize,String fileName) {
        String date = DateTimeUtil.format(LocalDate.now(),"yyyyMMdd");

        StringBuilder objectKey = new StringBuilder(date);
        objectKey.append(SLASH).append(fileSize).append(FILE_NAME_PREFIX_SEPARATOR).append(fileName);
        return objectKey.toString();
    }
}
